"use client"

import { useState } from "react"
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { Copy, Check } from "lucide-react"
import { apiCall, mockGenerators } from "@/lib/mock-api"
import { toast } from "@/hooks/use-toast"

interface ShareDialogProps {
  file: { id: number; fileName: string }
  open: boolean
  onOpenChange: (open: boolean) => void
}

export function ShareDialog({ file, open, onOpenChange }: ShareDialogProps) {
  const toLocalInputValue = (date: Date) => {
    const offsetDate = new Date(date.getTime() - date.getTimezoneOffset() * 60000)
    return offsetDate.toISOString().slice(0, 16)
  }

  const [password, setPassword] = useState("")
  const [usePassword, setUsePassword] = useState(false)
  const [shareLink, setShareLink] = useState("")
  const [copied, setCopied] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [expireTime, setExpireTime] = useState(() =>
    toLocalInputValue(new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)),
  )

  const handleCreateShare = async () => {
    setIsLoading(true)
    try {
      const data = await apiCall(
        "/api/shares",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            fileId: file.id,
            password: usePassword ? password : null,
            expireTime: new Date(expireTime).toISOString(),
          }),
        },
        undefined,
        mockGenerators.share,
      )

      const shareUrl = `${window.location.origin}/shared?shareId=${encodeURIComponent(data.id)}`
      setShareLink(shareUrl)

      toast({
        title: "分享链接已生成",
        description: "链接有效期为7天",
        variant: "success",
        duration: 3000,
      })
    } catch (error) {
      console.error("Failed to create share:", error)
    } finally {
      setIsLoading(false)
    }
  }

  const handleCopy = () => {
    navigator.clipboard.writeText(shareLink)
    setCopied(true)
    setTimeout(() => setCopied(false), 2000)

    toast({
      title: "已复制",
      description: "分享链接已复制到剪贴板",
      variant: "success",
      duration: 3000,
    })
  }

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>分享文件</DialogTitle>
          <DialogDescription>创建分享链接，让其他人可以查看此文件</DialogDescription>
        </DialogHeader>

        <div className="space-y-4 py-4">
          <div>
            <p className="text-sm font-medium mb-1">文件名</p>
            <p className="text-sm text-muted-foreground">{file.fileName}</p>
          </div>

          <div className="flex items-center justify-between">
            <Label htmlFor="password-toggle">设置访问密码</Label>
            <Switch
              id="password-toggle"
              checked={usePassword}
              onCheckedChange={setUsePassword}
              disabled={Boolean(shareLink)}
            />
          </div>

          {usePassword && (
            <div className="space-y-2">
              <Label htmlFor="password">访问密码</Label>
              <Input
                id="password"
                type="text"
                placeholder="设置4位数字密码"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                maxLength={4}
                disabled={Boolean(shareLink)}
              />
            </div>
          )}

          <div className="space-y-2">
            <Label htmlFor="expire-time">到期时间</Label>
            <Input
              id="expire-time"
              type="datetime-local"
              value={expireTime}
              onChange={(e) => setExpireTime(e.target.value)}
              min={toLocalInputValue(new Date())}
              disabled={Boolean(shareLink)}
            />
          </div>

          {!shareLink ? (
            <Button
              className="w-full"
              onClick={handleCreateShare}
              disabled={
                isLoading ||
                !expireTime ||
                Number.isNaN(new Date(expireTime).getTime()) ||
                new Date(expireTime).getTime() <= Date.now() ||
                (usePassword && password.length !== 4)
              }
            >
              {isLoading ? "生成中..." : "生成分享链接"}
            </Button>
          ) : (
            <div className="space-y-2">
              <Label>分享链接</Label>
              <div className="flex gap-2">
                <Input value={shareLink} readOnly />
                <Button variant="outline" size="icon" onClick={handleCopy}>
                  {copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
                </Button>
              </div>
              {usePassword && <p className="text-sm text-muted-foreground">访问密码: {password}</p>}
            </div>
          )}
        </div>
      </DialogContent>
    </Dialog>
  )
}
